package com.uiotsoft.small.app.service.deviceControl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.uiotsoft.small.app.entity.AppClient;
import com.uiotsoft.small.app.service.AppBaseControl;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DeviceControl extends AppBaseControl {
    private final static String model = "deviceControl";

    public DeviceControl(AppClient appClient) {
        super(appClient);
    }

    /**
     *设备控制
     * @param deviceId
     * @param properties
     * @return
     */
    public boolean controlBlock(int deviceId, String properties)  {
        JSONObject handlerData = handlerData(deviceId, properties);
        publishToHost(model, model, handlerData);
        String topic;
        String result;
        long start = System.currentTimeMillis();
        while (true){
            topic = appClient.getMyMqttClient().getTopic();
            result = appClient.getMyMqttClient().getResult();
            if (topic!= null && result != null){
                log.info("客户端接收成功……\n******topic：{}:\n******content{}",topic,result);
                if (topic.contains("deviceControl")){
                    String code = JSONUtil.parseObj(result).getJSONObject("payload").getStr("code");
                    if (code.equals("0")){
                        return true;
                    }else {
                        return false;
                    }

                }
            }
            long end = System.currentTimeMillis();
            if (end-start >10000){
                return false;
            }
        }
    }

    /**
     *设备控制
     * @param deviceId
     * @param properties
     * @return
     */
    public boolean control(int deviceId, String properties)  {
        JSONObject handlerData = handlerData(deviceId, properties);
        return publishToHost(model, model, handlerData);
    }

    public JSONObject handlerData(int deviceId, String properties){
        String payload = "{\"sn\":\"\",\"deviceId\":204,\"properties\":{},\"userUnique\":\"\",\"controlSources\":\"user\",\"controlSourcesIdentity\":\"\"}";
        JSONObject payloadJson = JSONUtil.parseObj(payload);
        payloadJson.put("sn", appClient.getSn());
        payloadJson.put("deviceId", deviceId);
        payloadJson.put("properties", JSONUtil.parseObj(properties));
        payloadJson.put("userUnique", appClient.getUserUnique());
        payloadJson.put("controlSourcesIdentity", appClient.getUserUnique());
        return payloadJson;
    }

    /**
     * 异常控制
     *
     * @param data
     * @return
     */
    public String abnormalControl(String data) {
        publishToHost(model, model, JSONUtil.parseObj(data));
        return null;
    }
}
